package com.yuzi.model.systemMo;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yuzi.model.BaseMo.BaseModel;

import java.util.List;

public class SysMenu extends BaseModel<SysMenu> {
    //已经采用BaseModel注入替代
    //public static final SysMenu dao = new SysMenu();

    public SysMenu findMenuById(Integer id){
        return this.findById(id);
    }

    public List<SysMenu> findAllMenuByNoDeal(){
        String sql = "select id,pid,name from sys_menu ORDER BY sort,id";
        return this.find(sql);
    }

    public List<SysMenu> findAllMenuByRoleNoDeal(Integer roleId){
        String sql = "SELECT sm.id,sm.pid,NAME FROM sys_menu sm " +
                " INNER JOIN sys_role_menu srm ON sm.id=srm.menu_id AND srm.role_id=" +roleId+
                "  ORDER BY sm.sort,sm.id";
        return this.find(sql);
    }

    public List<SysMenu> findAllMenuByUser(String username){
        String sql = "SELECT DISTINCT sm.* FROM sys_user su \n" +
                "\tINNER JOIN sys_user_role sur ON su.id = sur.user_id\n" +
                "\tINNER JOIN sys_role_menu srm ON sur.role_id = srm.role_id\n" +
                "\tINNER JOIN sys_menu sm ON sm.id = srm.menu_id\n" +
                "\tWHERE sm.isHidden = 0 \n" +
                "\tAND su.username = ?" +
                "\tOrder by sm.sort ,sm.id \n";
        return this.find(sql,username);
    }

    public List<Record> findAllMenu(){
        String sql = "SELECT sm.id,sm.pid,sm.url,sm.sort,sm.code,sm.icon,sm.name,sm.ishidden FROM sys_menu sm \n" +
                "ORDER BY sm.sort,sm.id ";
        return Db.find(sql);
    }

    public List<Record> findAllAuthMenuByRoleId(Integer roleId){
        String sql ="SELECT * FROM sys_menu sm \n" +
                "\tLEFT JOIN sys_role_menu srm ON sm.id = srm.menu_id AND srm.role_id = ?\n" +
                "\tORDER BY sm.sort,sm.id";
        return Db.find(sql,roleId);
    }

    public List<SysMenu> getChildMenu(int pid){
        String sql = "select * from sys_menu where pid = ?";
        return this.find(sql,pid);
    }

    public List<SysMenu> getRootAndParentMenu(){
        String sql = "select * from sys_menu where id = 0 or pid = 0 order by sort,id";
        return this.find(sql);
    }

    public int addMenu(SysMenu sysMenu){
        int maxIndex = getMaxIndex(this);
        boolean isSuc = sysMenu.set("id",maxIndex+1).save();
        if (isSuc)
            return sysMenu.getInt("id");
        else
            return 0;
    }

    public boolean updateMenu(SysMenu sysMenu){
        return sysMenu.update();
    }

    private List<SysMenu> children;

    public List<SysMenu> getChildren() {
        return children;
    }

    public void setChildren(List<SysMenu> children) {
        this.children = children;
    }
}
